#include "StdAfx.h"
#include "rtt_handler.h"

namespace fly {

	namespace jld{

		namespace server {

			rtt_handler::rtt_handler()
				:handler()
				,PROOF_COUNT_(5)
			{
			}

			bool rtt_handler::handle_recv(recv_buf& recv_buf, send_buf& send_buf, conn_info& conn_info)
			{
				if (RTT != recv_buf.pid())
				{
					return handler::handle_recv(recv_buf, send_buf, conn_info);
				}
				LOG_INFO("Handle round trip time");
				RoundTripTime rtt;
				if (0 == recv_buf.buf().size())
				{
					rtt.set_is_proof(true);
					rtt.set_srv_time(timestamp->cur_mill_sec());
					return send_buf.serialize_to_send(RTT, target_, rtt);
				}

				if(!recv_buf.parse_from_recv(rtt))
				{
					LOG_EMER("Parse move faild");
					return false;
				}
				__int64 tmp_rtt =  timestamp->cur_mill_sec() - rtt.srv_time();
				__int64 tmp_dt = (rtt.srv_time() +  conn_info.rtt() / 2 - rtt.cln_time());

				if (PROOF_COUNT_ != conn_info.add_sync_time(tmp_rtt, tmp_dt))
				{
					rtt.set_is_proof(true);
					rtt.set_srv_time(timestamp->cur_mill_sec());
					return send_buf.serialize_to_send(RTT, target_, rtt);
				}


				if (!conn_info.cal_sync_time())
				{
					return false;
				}
				rtt.set_is_proof(false);
				rtt.set_rtt(conn_info.rtt());
				rtt.set_delta_time(conn_info.delta_time());
				if (!send_buf.serialize_to_send(RTT, target_, rtt))
				{
					return false;
				}

				//go to move handler
				recv_buf.pid() = MOVE;
				return handler::handle_recv(recv_buf, send_buf, conn_info);
			}

		}
	}
}